<template>
  <div style="height: 100%;width: calc(100% - 40px);">

    <div class="commentIconFixed">
      <!--      收藏、取消收藏-->
      <div class="commentIcon">
        <img :src="collectImg" @click="toCollect">
        <div>{{ myObj.starCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 10px;">
        <img src="assets/theme/img/comment_img.png" @click="toComment">
        <div>{{ myObj.commentCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 10px;">
        <img :src="agreeImg" @click="agreeOrNotAgree(true)">
        <div>{{ myObj.agreeCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 12px;">
        <img :src="notAgreeImg" @click="agreeOrNotAgree(false)">
        <div>{{ myObj.notAgreeCount }}</div>
      </div>
    </div>

    <el-row :span="24">
      <el-col :span="13" style="line-height: 34px;">
        <i
          style="font-weight: 700;font-size: 16px;margin-right: 20px;cursor: pointer"
          class="el-icon-arrow-left"
          @click="returnPage"
        />
        <span style="font-weight: 700;font-size: 16px;">{{ myObj.title }}</span>
      </el-col>
      <el-col :span="11" style="text-align: right">
        <el-button v-if="permission.workbenchKbpUpdate" type="primary" size="small" @click="editArticle">修改</el-button>
        <el-button v-if="permission.workbenchKbpDelete" type="primary" size="small" style="margin-left: 5px;" @click="delArticle">删除</el-button>
      </el-col>
    </el-row>
    <el-divider style="margin: 10px;" />

    <el-row :span="24" class="know-title">
      <el-col :span="9">
        <span class="line-height">{{ myObj.realName }} • 发表于：{{ myObj.createTime }}</span>
      </el-col>
      <el-col :span="7">
        <span>业务类型：</span>
        <span class="line-height">{{ myObj.businessNames }}</span>
      </el-col>
      <el-col :span="8">
        <span>关键字：</span>
        <span class="line-height">{{ myObj.keyWord }}</span>
      </el-col>
    </el-row>

    <el-row v-if="myObj.summary" :span="24" class="know-title">
      <el-col class="line-height" :span="3"><strong>摘要：</strong></el-col>
      <el-col class="line-height" :span="21">
        {{ myObj.summary }}
      </el-col>
    </el-row>

    <el-row :span="24" class="know-content">
      <el-col class="line-height" :span="24"><strong>正文：</strong></el-col>
      <el-col class="line-height" :span="24" style="text-indent: 24px">
        <mavon-editor
          ref="md"
          v-model="myObj.mdContent"
          :box-shadow="false"
          :toolbars-flag="false"
          default-open="preview"
          :subfield="false"
          preview-background="#ffffff"
        />
      </el-col>
    </el-row>

    <el-row :span="24" class="know-title">
      <el-col class="line-height" :span="3"><strong>附件：</strong></el-col>
      <el-col class="line-height" :span="21">
        <div
          v-for="file in myObj.knowledgeArticleFileList"
          style="cursor: pointer;float: left;line-height: 30px;"
          @click="download(file)"
        >
          <i class="el-icon-document-add" style="padding-left: 5px;" />
          <span style="margin-left: 10px;">{{ file.name }}</span>
        </div>
      </el-col>
    </el-row>

    <el-row v-if="permission.aiSwitch && linkKnowSwitch" :span="24" class="know-title">
      <el-col class="line-height" :span="24"><strong>关联知识</strong></el-col>
      <el-col :span="24">
        <el-row style="margin-top: 10px;">
          <el-col :span="24">
            <div id="graphDiv" style="width:100%;height:500px;clear: both" />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row :span="24" class="know-title">
      <el-col class="line-height" :span="24"><strong>评论</strong></el-col>
      <el-col :span="24">
        <el-row id="commentRow">
          <el-col :span="21">
            <el-input
              v-model="content"
              style="border-radius: 0px;"
              placeholder="写下你的评论..."
              size="small"
              resize="none"
              maxlength="300"
            />
          </el-col>
          <el-col :span="2" style="text-align: right">
            <el-button type="primary" size="small" @click="addComment">发 布</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row :span="24">
      <div v-for="(c, index) in myObj.commentList" :key="index" class="commentDiv">
        <el-col style="width: 40px;height: 40px;margin: 5px 5px 10px 0px;">
          <img
            v-if="c.avatar"
            :src="headImgUrl + c.avatar"
            onerror="this.src = 'assets/theme/img/default_user_avatar.png'; this.onerror = null;"
          >
          <img v-else src="assets/theme/img/default_user_avatar.png">
        </el-col>
        <el-col style="width: calc(100% - 50px);float: right;">
          <el-col :span="12" class="commentName" style="height:33.6px;width:50%;">{{ c.realName }}</el-col>
          <el-col :span="12" class="commentName" style="text-align: right;">{{ c.createTime }}</el-col>
          <el-col :span="24" class="line-height">{{ c.content }}</el-col>
          <el-col v-if="c.canDelete == 1" :span="24" style="text-align: right;line-height: 20px;">
            <i class="el-icon-delete" style="cursor: pointer" @click="delComment(c.id)" />
          </el-col>
        </el-col>
        <div v-if="index !== 0" :span="24">
          <el-divider />
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
import { getArticleById, delArticle, addComment, collectOrNotCollect, delComment, agreeOrNotAgree } from '@/api/kbp'
import { mapGetters } from 'vuex'
import echarts from 'echarts'
export default {
  name: 'ArticleDetail',
  data() {
    return {
      linkKnowSwitch: !window.Settings.multiTenantSwitch,
      id: this.$route.query.id,
      myObj: {},
      tags: [],
      content: '',
      headImgUrl: window.CONFIG.restIps + '/eurm/if/base/file/public/getFilePreview?code=',
      agreeImg: 'assets/theme/img/agree_img.png',
      notAgreeImg: 'assets/theme/img/not_agree_img.png',
      collectImg: 'assets/theme/img/default_collect.png'
    }
  },
  computed: {
    ...mapGetters(['permission'])
  },
  watch: {
    '$route': {
      immediate: true,
      handler(to, from) {
        if (to.name === 'kbpDetail') {
          console.log('detail watch route!!!')
          this.id = to.params.id || sessionStorage.getItem('knowledgeId')
          // 在mounted调用的methods里的方法
          this.myObj = {}
          this.initData()
        }
      }
    }
  },
  mounted() {

  },
  components: {},
  methods: {
    // 收藏、取消收藏
    toCollect() {
      let type = 1
      if (this.myObj.starStatus == 1) {
        type = 2
      }
      const params = {
        type: type,
        knowledgeArticleId: this.id
      }
      collectOrNotCollect(params).then(res => {
        if (res.data.code == 200) {
          this.initData()
          this.$message({ message: params.type == 1 ? '收藏成功！' : '取消收藏成功！', type: 'success' })
        }
      })
    },
    // 跳转到评论界面
    toComment() {
      const returnEle = document.querySelector('#commentRow')
      if (returnEle) {
        returnEle.scrollIntoView(true)
      }
    },
    // 点赞/取消点赞(1赞2踩3取消赞4取消踩5赞->踩6踩->赞)
    agreeOrNotAgree(flag) {
      const that = this
      if (that.myObj.agreeStatus == 0 && that.myObj.notAgreeStatus == 0) {
        flag ? that.type = 1 : that.type = 2
      } else if (that.myObj.agreeStatus == 0 && that.myObj.notAgreeStatus == 1) {
        flag ? that.type = 6 : that.type = 4
      } else if (that.myObj.agreeStatus == 1 && that.myObj.notAgreeStatus == 0) {
        flag ? that.type = 3 : that.type = 5
      }
      const params = {
        type: that.type,
        knowledgeArticleId: that.id
      }
      agreeOrNotAgree(params).then(res => {
        if (res.data.code == 200) {
          let message = '点赞成功！'
          if (that.type == 3) {
            message = '取消点赞成功！'
          } else if (that.type == 2 || that.type == 5) {
            message = '点踩成功！'
          } else if (that.type == 4) {
            message = '取消点踩成功！'
          }
          console.log('type is: ' + that.type)
          that.$message({ message: message, type: 'success' })
          that.initData()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 删除评论
    delComment(id) {
      const that = this
      const params = {
        id: id,
        knowledgeArticleId: that.id
      }
      delComment(params).then(res => {
        if (res.data.code == 200) {
          that.$message({ message: '删除成功', type: 'success' })
          that.initData()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 发布评论
    addComment() {
      const that = this
      const params = {
        content: that.content,
        knowledgeArticleId: that.id
      }
      if (!that.content) {
        that.$message({ message: '请填写评论内容', type: 'warning' })
        return
      }
      addComment(params).then(res => {
        if (res.data.code == 200) {
          that.$message({ message: '评论成功', type: 'success' })
          that.content = ''
          that.initData()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 返回上一页
    returnPage() {
      const path = '/kbp'
      this.$router.push({
        path: path
      })
    },
    // 暂未用到
    toArticleHome(id) {
      this.$router.$avueRouter.closeTag()
      const path = '/knowledge/index'
      this.$router.push({
        path: path,
        query: {
          knowledgeCategoryId: id
        }
      })
    },
    // 修改按钮事件
    editArticle() {
      let path = '/kbpArticleAdd'
      if (this.myObj.type == 2) {
        path = '/kbpQuestionAdd'
      }
      this.$router.push({
        path: path,
        query: {
          id: this.id,
          knowledgeType: this.myObj.type
        }
      })
    },
    // 删除按钮事件
    delArticle() {
      const that = this
      this.$confirm('确认删除此知识点?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delArticle({ ids: that.id }).then(res => {
          if (res.data.code == 200) {
            that.$message({ message: '删除成功', type: 'success' })
            // that.$router.$avueRouter.closeTag();
            that.$router.go(-1)
          }
        })
      })
    },
    // 下载附件
    download(file) {
      if (file && file.path) {
        window.open(window.CONFIG.fileServer + '/get?filename=' + file.path)
      } else {
        this.$message({ message: '附件路径为空，不能下载！', type: 'warning' })
      }
    },
    initData() {
      const self = this
      if (self.id) {
        getArticleById({ id: self.id }).then(res => {
          self.myObj = res.data.data
          if (self.myObj.starStatus == 1) {
            self.collectImg = 'assets/theme/img/select_collect.png'
          } else {
            self.collectImg = 'assets/theme/img/default_collect.png'
          }
          if (self.myObj.agreeStatus == 1) {
            self.agreeImg = 'assets/theme/img/confirm_agree_img.png'
          } else {
            self.agreeImg = 'assets/theme/img/agree_img.png'
          }
          if (self.myObj.notAgreeStatus == 1) {
            self.notAgreeImg = 'assets/theme/img/confirm_not_agree_img.png'
          } else {
            self.notAgreeImg = 'assets/theme/img/not_agree_img.png'
          }
          if (self.myObj.tags) {
            self.tags = self.myObj.tags.split(',')
          }
          if (self.myObj.graphStr) {
            setTimeout(function() {
              var myChart = echarts.init(document.getElementById('graphDiv'))
              var graph = JSON.parse(self.myObj.graphStr)
              var categories = []
              var keyWordArr = self.myObj.keyWord.split(',')
              for (let i = 0; i < keyWordArr.length; i++) {
                categories[i] = {
                  name: keyWordArr[i]
                }
              }
              graph.nodes.forEach(function(node) {
                node.itemStyle = null
                // node.value = node.symbolSize;
                node.symbolSize /= 1.5
                node.label = {
                  show: node.symbolSize > 30
                }
                node.category = node.attributes.modularity_class
              })
              const option = {
                tooltip: {},
                legend: [{
                  // selectedMode: 'single',
                  data: categories.map(function(a) {
                    return a.name
                  })
                }],
                animationDuration: 1500,
                animationEasingUpdate: 'quinticInOut',
                series: [
                  {
                    name: '关联知识',
                    type: 'graph',
                    layout: 'none',
                    data: graph.nodes,
                    links: graph.links,
                    categories: categories,
                    roam: true,
                    focusNodeAdjacency: true,
                    itemStyle: {
                      borderColor: '#fff',
                      borderWidth: 1,
                      shadowBlur: 10,
                      shadowColor: 'rgba(0, 0, 0, 0.3)'
                    },
                    label: {
                      position: 'right',
                      formatter: '{b}'
                    },
                    lineStyle: {
                      color: 'source',
                      curveness: 0.3
                    },
                    emphasis: {
                      lineStyle: {
                        width: 10
                      }
                    }
                  }
                ]
              }
              myChart.setOption(option)
              myChart.on('click', function(param) {
                if (param.dataType == 'node') {
                  self.$router.push({
                    path: '/kbpDetail',
                    query: {
                      id: param.data.id
                    }
                  })
                }
              })
            }, 500)
          }
        })
      } else {
        console.log('init id is null!!!')
      }
    }
  }
}
</script>

<style scoped>

  .el-divider--horizontal {
    margin: 10px 0px 0px;
  }

  .v-note-wrapper {
    height: auto;
    min-height: 0px;
  }

  .commentIconFixed {
    position: fixed;
    overflow: hidden;
    right: -25px;
    bottom: 45%;
    z-index: 999;
    width: 80px;
  }

  .commentIcon img {
    width: 20px;
    height: 20px;
    vertical-align: middle;
    cursor: pointer
  }

  .commentIcon div {
    display: inline-block;
    height: 20px;
    margin-left: 5px;
    color: #666666;
    font-size: 14px;
  }

  .line-height {
    line-height: 28px;
  }

  .markdown-body {
    border: none;
  }

  .know-title {
    margin: 20px 0px;
    color: #8F8F91;
    font-size: 14px;
  }

  .know-content {
    color: #8F8F91;
    font-size: 14px;
  }

  .know-content .markdown-body {
    font-size: 14px;
    padding: 0px;
    line-height: 24px;
    color: #333333;
  }

  .commentDiv {
    width: 100%;
    height: auto;
    overflow: hidden;
  }

  .commentDiv .el-divider--horizontal {
    margin: 0px;
  }

  .commentDiv img{
    width: 100%;
    height: 100%;
    margin: 10px 5px 10px 0px;
  }

  .commentName{
    line-height: 34px;
    color: #8F8F91;
    font-size: 13px;
  }

</style>
